package xiaohui

import (
	"math/rand"
	"time"
)

//  抢红包算法
// 二倍均值法
// 假设剩余红包金额为m元，剩余人数为n 那么有如下公式
// 每次抢到的金额= 随机区间[0.01, m/n*2-0.01]
// 保证了每次随机金额的平均值是相等的，不会因为抢红包的先后顺序而造成不公平

func DivideRedPackage(total float64, people int) []float64 {
	maxPeople := int(total * 100)
	if people <= maxPeople {
		maxPeople = people
	}
	result := make([]float64, maxPeople)
	restPeople := maxPeople
	restTotal := int(total * 100)
	for i := 0; i < maxPeople-1; i++ {
		// 随机范围 [1,剩余人均金额的2倍-1]分
		amount := rand.Intn(restTotal/restPeople*2-1) + 1
		restTotal -= amount
		restPeople--
		result[i] = float64(amount) / 100
	}
	result[maxPeople-1] = float64(restTotal) / 100

	return result
}

func init() {
	rand.Seed(time.Now().Unix())
}
